package com.gqzm.side.common.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: {@link CloudPlatformSocketClient}
 * @description: 连接离娄云平台socket 客户端
 * @author: peter qin
 * @date: 2023 12 15
 * @version: 1.0
 **/
@Slf4j
@Component
public class CloudPlatformSocketClient {
    private EventLoopGroup group = new NioEventLoopGroup(1);
    private static int port = 8081;
    private static String host;

    @Value("${gqzm.platform.socket.host:192.168.2.111}")
    public void setHost(String ip) {
        host = ip;
    }

    @Value("${gqzm.platform.socket.port:8081}")
    public void setIp(Integer param) {
        port = param;
    }


    public void start() throws InterruptedException {
        try {
            Bootstrap bootstrap = new Bootstrap();
            // 客户端不需要处理连接 所以一个线程组就够了
            bootstrap.group(group)
                    // 连接通道
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .option(ChannelOption.TCP_NODELAY, true)
                    // 数据处理
                    .handler(new BootNettyChannelInitializer());
            ChannelFuture future = bootstrap.connect();
            //客户端断线重连逻辑
            future.addListener((ChannelFutureListener) future1 -> {
                if (future1.isSuccess()) {
                    log.info("连接Netty服务端成功");
                } else {
                    log.info("连接失败，进行断线重连");
                    future1.channel().eventLoop().schedule(() -> {
                        try {
                            start();
                        } catch (InterruptedException e) {
                            log.error("socket执行异常", e);
                        }
                    }, 20, TimeUnit.SECONDS);
                }
            });
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.info("服务端异常");
        } finally {
            group.shutdownGracefully();
        }
    }


}
